package leetcode.offer;

import leetcode.base.TreeNode;

/**
 * ClassName: Offer55II_IsBalanced
 * Description: leetcode-剑指offer 55 II 平衡二叉树
 * date: 2021-11-13 9:22
 *
 * @author liyifan
 */
public class Offer55II_IsBalanced {
    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        else
            return recur(root) != -1;
    }

    public int height(TreeNode root) {
        if (root == null)
            return 0;
        else
            return Math.max(height(root.left), height(root.right)) + 1;
    }

    public int recur(TreeNode treeNode){
        if (treeNode == null)
            return 0;
        int left = recur(treeNode.left);
        if (left == -1)
            return -1;
        int right = recur(treeNode.right);
        if (right == -1)
            return -1;
        return Math.abs(left - right) < 2 ? Math.max(left, right) + 1: -1;
    }
}
